﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.Base;
using UFIDA.U9.Base.Organization;
using UFIDA.U9.Base.UOM;
using UFIDA.U9.CBO.FI.CommonFIHelper;
using UFIDA.U9.CBO.HR.Operator;
using UFIDA.U9.CBO.MFG.CostElement;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.CBO.QC.QCSchema;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.CBO.SCM.PickBy;
using UFIDA.U9.CBO.SCM.Supplier;
using UFIDA.U9.ER.ERBP;
using UFIDA.U9.ISV.Item.Proxy;
using UFIDA.U9.SM.DealerSO;
using UFSoft.UBF.Business;
using UFSoft.UBF.Util.DataAccess;

namespace ufida.u9.ait.openapi
{
    internal class ItemMasterBase
    {
        /// <summary>
        /// 料品下发
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static ItemMaster SendItem(ItemMasterSendDTOData dto, ItemMaster item)
        {
            Organization org = Organization.Finder.Find($"Code='{dto.Org}'");
            if (org == null)
            {
                throw new Exception($"查找目标组织失败,组织编码:[{dto.Org}]");
            }
            OnlineSendObj bp = new OnlineSendObj();
            bp.EntitySent = item.Key;
            bp.FromOrg = Context.LoginOrg.Key;
            bp.ToOrgList = new List<Organization.EntityKey>
                    {
                        org.Key
                    };
            bp.Do();

            return item;
        }

        /// <summary>
        /// 料品从当前组织下发到其他所有组织
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static ItemMaster SendItem(ItemMaster item)
        {
            List<Organization.EntityKey> toorgs = new List<Organization.EntityKey>();
            List<Organization> orgs = EntityUtils.GetAllOrgs();
            foreach(var org in orgs)
            {
                if (org.Code != Context.LoginOrg.Code)
                {
                    toorgs.Add(org.Key);
                }
            }

            if(toorgs.Count > 0)
            {
                OnlineSendObj bp = new OnlineSendObj();
                bp.EntitySent = item.Key;
                bp.FromOrg = Context.LoginOrg.Key;
                bp.ToOrgList = toorgs;
                bp.Do();
            }

            return item;
        }

        /// <summary>
        /// 料品审核
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static ItemMaster ApproveItem(ItemMasterSendDTOData dto, ItemMaster item)
        {
            if (item.State == ItemStateEnum.Verified)
                throw new Exception($"料号[{item.Code}]已审核!");

            ItemMasterApproveBP bp = new ItemMasterApproveBP();
            bp.ItemMaster = item.Key;
            bp.ItemSysVersion = item.SysVersion;
            bp.Do();

            return item;
        }
        /// <summary>
        /// 料品修改
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static ItemMasterData UpdateItem(CopyOfItemMasterDTOData dto, ItemMaster item)
        {
            SetDTODefault(dto, item);
            //DTO转换
            UFIDA.U9.ISV.Item.ItemMasterDTOData dto1 = new UFIDA.U9.ISV.Item.ItemMasterDTOData();
            DTOUtils.DTOPropCopy(dto, dto1);
            //项目个性化处理
            DoProjectSpec(item, dto1);
            //新增/修改前处理默认值
            SetDefault(dto1, item);

            //修改逻辑
            BatchModifyItemByDTOSRVProxy proxy = new BatchModifyItemByDTOSRVProxy();
            proxy.ItemMasterDTOs = new List<UFIDA.U9.ISV.Item.ItemMasterDTOData>() { dto1 };
            proxy.ContextDTO = U9Utils.CreateContext();
            List<ItemMasterData> ret = proxy.Do();

            //新增后修改逻辑
            U9Utils.ClearCache();
            SetAfter(dto, dto1, ret[0].ID);

            if (ret != null && ret.Count > 0)
                return ret[0];
            else
                return null;
        }
        /// <summary>
        /// 项目个性化处理
        /// </summary>
        /// <param name="item"></param>
        /// <param name="dto1"></param>
        /// <exception cref="Exception"></exception>
        private static void DoProjectSpec(ItemMaster item, UFIDA.U9.ISV.Item.ItemMasterDTOData dto1)
        {
            //修改校验
            if (AITConstant.CurProject == AITConstant.AITProjectType.klw)
            {
                //凯路威项目 料品修改校验
                if (dto1.ItemFormAttribute > -1 && dto1.ItemFormAttribute != item.ItemFormAttribute.Value)
                    throw new Exception($"料品[{item.Code}]形态属性不能修改");
                if (dto1.InventoryUOM != null && dto1.InventoryUOM.Code != item.InventoryUOM.Code)
                    throw new Exception($"料品[{item.Code}]库存主单位不能修改");
                if (dto1.InventorySecondUOM != null && dto1.InventorySecondUOM.Code != item.InventorySecondUOM.Code)
                    throw new Exception($"料品[{item.Code}]库存单位不能修改");
                if (dto1.SalesUOM != null && dto1.SalesUOM.Code != item.SalesUOM.Code)
                    throw new Exception($"料品[{item.Code}]销售单位不能修改");
                if (dto1.PurchaseUOM != null && dto1.PurchaseUOM.Code != item.PurchaseUOM.Code)
                    throw new Exception($"料品[{item.Code}]采购单位不能修改");
                if (dto1.PriceUOM != null && dto1.PriceUOM.Code != item.PriceUOM.Code)
                    throw new Exception($"料品[{item.Code}]计价单位不能修改");
                if (dto1.ManufactureUOM != null && dto1.ManufactureUOM.Code != item.ManufactureUOM.Code)
                    throw new Exception($"料品[{item.Code}]生产单位不能修改");
                if (dto1.MaterialOutUOM != null && dto1.MaterialOutUOM.Code != item.MaterialOutUOM.Code)
                    throw new Exception($"料品[{item.Code}]领料单位不能修改");
                if (dto1.CostUOM != null && dto1.CostUOM.Code != item.CostUOM.Code)
                    throw new Exception($"料品[{item.Code}]成本单位不能修改");
                if (dto1.PurchaseInfo != null && dto1.PurchaseInfo.ChargeProcessMode > -1
                    && dto1.PurchaseInfo.ChargeProcessMode != item.PurchaseInfo.ChargeProcessMode.Value)
                    throw new Exception($"料品[{item.Code}]费用料处理不能修改");
            }
        }

        /// <summary>
        /// 设置传入DTO的默认值
        /// </summary>
        /// <param name="dto">传入dto</param>
        /// <param name="be">料品</param>
        private static void SetDTODefault(CopyOfItemMasterDTOData dto, ItemMaster be)
        {
            if (string.IsNullOrEmpty(dto.MainItemCategory?.Code))
                throw new Exception("MainItemCategory为空");

            if (be == null)
            {
                //新增
                //物料自动编码处理
                if (dto.Code == "Code1" || dto.Code == "Code2"
                || dto.Code.StartsWith("PubDescSeg") || dto.Code.StartsWith("PrivateDescSeg"))
                {
                    //自动编号
                    if (string.IsNullOrEmpty(dto.Prefix)) throw new Exception("Prefix为空");
                    dto.Code = $"{dto.Prefix}自动编号";
                }
            }
            else
            {
                //修改
                dto.ID = be.ID;
                dto.Code = be.Code;
            }
        }

        /// <summary>
        /// 料品新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static ItemMasterData CreateItem(CopyOfItemMasterDTOData dto)
        {
            SetDTODefault(dto, null);
            //DTO转换
            UFIDA.U9.ISV.Item.ItemMasterDTOData dto1 = new UFIDA.U9.ISV.Item.ItemMasterDTOData();
            DTOUtils.DTOPropCopy(dto, dto1);
            //新增/修改前处理默认值
            SetDefault(dto1, null);
            //新增逻辑
            BatchCreateItemByDTOSRVProxy proxy = new BatchCreateItemByDTOSRVProxy();
            proxy.ItemMasterDTOs = new List<UFIDA.U9.ISV.Item.ItemMasterDTOData>() { dto1 };
            proxy.ContextDTO = U9Utils.CreateContext();
            List<ItemMasterData> ret = proxy.Do();

            //新增后修改逻辑
            SetAfter(dto, dto1, ret[0].ID);

            //新增后自动下发
            //SendItem(item);

            if (ret != null && ret.Count > 0)
                return ret[0];
            else
                return null;
        }

        private static void SetAfter(CopyOfItemMasterDTOData dto
            , UFIDA.U9.ISV.Item.ItemMasterDTOData dto1
            , long itemid)
        {
            ItemMaster item;
            using (ISession session = Session.Open())
            {
                item = ItemMaster.Finder.FindByID(itemid);
                if (item == null)
                    throw new Exception("物料修改查找实体失败!");
                
                if (dto.MfgInfo != null && dto.MfgInfo.CostElement1 != null)
                {
                    //成本要素
                    CostElement costElement = EntityUtils.GetEntityByCode<CostElement>(dto.MfgInfo.CostElement1.Code);
                    item.MfgInfo.CostElement = costElement.ID;
                }

                if (dto.InventoryInfo != null)
                {
                    //拣货规则
                    if (!String.IsNullOrEmpty(dto.InventoryInfo.PickingRuleDTO?.Code))
                    {
                        PickBy pickBy = EntityUtils.GetEntityByCode<PickBy>(dto.InventoryInfo.PickingRuleDTO.Code);
                        item.InventoryInfo.PickingRule = pickBy.ID;
                    }
                }

                //质量信息处理
                if (dto.InspectionInfo != null)
                {
                    //进货检验处理
                    if (dto.InspectionInfo.ReceiptInspectRule1 != null
                        && !string.IsNullOrEmpty(dto.InspectionInfo.ReceiptInspectRule1.Code))
                    {
                        if (dto.InspectionInfo.ReceiptInspectRuleVer1 == null)
                            throw new Exception("质量信息[ReceiptInspectRuleVer]不能为空");
                        string path = $"Code='{dto.InspectionInfo.ReceiptInspectRule1.Code}' and Version='{dto.InspectionInfo.ReceiptInspectRuleVer1.Code}'";
                        QCSchema qc = EntityUtils.GetEntityByPath<QCSchema>(path);
                        item.InspectionInfo.ReceiptInspectRule = qc.QCSchemaHeadKey.ID;
                        item.InspectionInfo.ReceiptInspectRuleVer = qc.ID;
                    }
                }

                session.Commit();
            }
        }

        /// <summary>
        /// 设置默认值
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="be"></param>
        private static void SetDefault(UFIDA.U9.ISV.Item.ItemMasterDTOData dto, ItemMaster be)
        {
            //设置默认值
            //状态=已核准
            dto.State = 2;
            //组织=登录组织
            if (dto.Org == null)
            {
                dto.Org = new CommonArchiveDataDTOData
                {
                    ID = Context.LoginOrg.ID,
                    Code = Context.LoginOrg.Code,
                };
            }
            //主分类
            if (String.IsNullOrEmpty(dto.MainItemCategory?.Code))
                throw new Exception("MainItemCategory为空");
            ItemCategory cat = EntityUtils.GetMainItemCategory(dto.MainItemCategory.Code);
            dto.MainItemCategory.ID = cat.ID;//设置ID,避免主分类编码重复导致报错
            //计量单位
            //计量单位只是在新增时赋值,修改时不再赋值
            if (dto.InventoryUOM != null && be==null)
            {
                UOM uom = EntityUtils.GetEntityByCode<UOM>(dto.InventoryUOM.Code);
                dto.InventoryUOM.ID = uom.ID;
                if (dto.InventorySecondUOM == null)
                {
                    //库存单位
                    dto.InventorySecondUOM = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
                if (dto.SalesUOM == null)
                {
                    //销售单位
                    dto.SalesUOM = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
                if (dto.PurchaseUOM == null)
                {
                    //采购单位
                    dto.PurchaseUOM = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
                if (dto.PriceUOM == null)
                {
                    //计价单位
                    dto.PriceUOM = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
                if (dto.ManufactureUOM == null)
                {
                    //生产单位
                    dto.ManufactureUOM = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
                if (dto.MaterialOutUOM == null)
                {
                    //领料单位
                    dto.MaterialOutUOM = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
                if (dto.CostUOM == null)
                {
                    //成本单位
                    dto.CostUOM = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
                if (dto.WeightUom == null)
                {
                    //重量单位
                    dto.WeightUom = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
                if (dto.BulkUom == null)
                {
                    //体积单位
                    dto.BulkUom = new CommonArchiveDataDTOData { ID = uom.ID, Code = dto.InventoryUOM.Code };
                }
            }

            //币种
            if (dto.CostCurrency == null)
            {
                dto.CostCurrency = new CommonArchiveDataDTOData
                {
                    Code = "C001"
                };
            }

            //库存
            if (dto.InventoryInfo == null)
            {
                dto.InventoryInfo = new UFIDA.U9.ISV.Item.ItemInvInfoDTOData();
            }
            // 规划方法 = MRP规划
            dto.InventoryInfo.InventoryPlanningMethod = 4;
            // 	采购控制方法=最高存量限制
            dto.InventoryInfo.PurchaseControlMode = 1;

            //计划
            if (dto.MrpInfo == null)
            {
                dto.MrpInfo = new UFIDA.U9.ISV.Item.ItemMRPInfoDTOData();
            }
            //计划方法=MRP
            dto.MrpInfo.MRPPlanningType = 1;

            //生产信息
            if (dto.MfgInfo == null)
            {
                dto.MfgInfo = new UFIDA.U9.ISV.Item.ItemMFGInfoDTOData();
            }
            // 产出率
            dto.MfgInfo.BuildShrinkageRate = 1;
            //允许超额领料
            if (dto.MfgInfo.IsAllowExcessMaterial)
            {
                //dto.MfgInfo.IsSueOverType = 0; //备料超额类型
                //dto.MfgInfo.StandardMaterialScale = 1;
            }
            else
            {
                dto.MfgInfo.IsSueOverType = -1; //备料超额类型
            }
            if (AITConstant.CurProject == AITConstant.AITProjectType.tyxm)
            {
                //ECN控制 天元项目
                dto.MfgInfo.IsECNControl = true;
            }

            //采购信息
            if (dto.PurchaseInfo == null)
            {
                dto.PurchaseInfo = new UFIDA.U9.ISV.Item.ItemPurchaseInfoDTOData();
            }
            //税组合=13%
            if (dto.PurchaseInfo.PurchaseTaxSchedule == null)
            {
                dto.PurchaseInfo.PurchaseTaxSchedule = new CommonArchiveDataDTOData
                {
                    Code = "YZ02"
                };
            }
            //采购部门
            if (dto.PurchaseInfo.Buyer != null && !string.IsNullOrEmpty(dto.PurchaseInfo.Buyer.Code))
            {
                Operators operators = EntityUtils.GetEntityByCode<Operators>(dto.PurchaseInfo.Buyer.Code);
                dto.PurchaseInfo.PurchaseDepartment = new CommonArchiveDataDTOData()
                {
                    ID = operators.Dept.ID,
                    Code = operators.Dept.Code,
                };
            }
            if (AITConstant.CurProject == AITConstant.AITProjectType.tyxm)
            {
                //收货程序 = 收货-点收-入库 天元项目
                dto.PurchaseInfo.ReceiptModeAllowModify = true;
                dto.PurchaseInfo.ReceiptMode = ReceiptModeEnum.ArriveEyeballingConfirm.Value;
            }

            //收货方式
            if (dto.ItemFormAttribute == 18)
            {
                //料品形态属性=资产 时,收货方式=收货至固定资产 3
                dto.PurchaseInfo.ReceiptType = 3;
            }
            
            //销售信息
            if (dto.SaleInfo == null)
            {
                dto.SaleInfo = new UFIDA.U9.ISV.Item.ItemSaleInfoDTOData();
            }
            //税组合=13%
            if (dto.SaleInfo.SaleTaxSchedule == null)
            {
                dto.SaleInfo.SaleTaxSchedule = new CommonArchiveDataDTOData
                {
                    Code = "YZ02"
                };
            }

            if (dto.InspectionInfo == null)
            {
                //检验方案默认为空
                dto.InspectionInfo = new UFIDA.U9.ISV.Item.ItemInspectionInfoDTOData();
                //dto.InspectionInfo.ReceiptInspectRule = 0;//进货质检
                //dto.InspectionInfo.ReceiptInspectRuleVer = 0;//进货质检版本
                //dto.InspectionInfo.BuildCompleteCheckUpRule = 0;//完工质检
                //dto.InspectionInfo.BuildCompleteCheckUpRuleVer = 0;//完工质检版本
            }

        }
    }
}
